<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addBtn('addType')">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.importconfig_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)">查看</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
      <template slot-scope="{ row }" slot="isExecuteDelete">
        <el-tag>{{ row.isExecuteDelete ? '是' : '否' }}</el-tag>
      </template>
    </avue-crud>
    <!--  v-if="showDialog" -->
    <el-dialog ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" v-if="showDialog" :close-on-click-modal="dialogClose" @close="closeDialog">
      <el-tabs type="border-card" v-model="tabsIndex">
        <el-tab-pane label="基本数据" name="1">
          <avue-form ref="basicPropertiesForm" v-model="model" :option="basicPropertiesOption"></avue-form>
        </el-tab-pane>
        <el-tab-pane v-if="model.type == 'DATABASE'" label="数据源配置" name="2">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">写入数据源</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary" @click="openCommonModal('writeData')">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" size="mini" type="danger" @click="onHandleDelete('warehousePropertiesCrud1')"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="warehousePropertiesCrud1"
            v-model="model"
            :data="writeDataSourceMap"
            :option="warehousePropertiesOption1"
            @cell-click="onHandleWriteSelect"
          ></avue-crud>
          <div class="top-title-flex">
            <i class="el-icon-refresh-left top-title-flex">读取数据源</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary" @click="openCommonModal('readData')">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" size="mini" type="danger" @click="onHandleDelete('warehousePropertiesCrud2')"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud ref="warehousePropertiesCrud2" v-model="model" :data="readDataSourceMap" :option="warehousePropertiesOption2"></avue-crud>
        </el-tab-pane>
        <el-tab-pane v-if="model.type == 'DATABASE'" label="SQL数据配置" name="3">
          <avue-form ref="SqlPropertiesForm" v-model="model" :option="SqlPropertiesOption"></avue-form>
        </el-tab-pane>
        <el-tab-pane label="数据映射配置" name="4">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称(回车确认)</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary" @click="addDataSourceRow('DataPropertiesCrud')">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" @click="onHandleDelete('DataPropertiesCrud')" size="mini" type="danger"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="DataPropertiesCrud"
            v-model="model"
            :data="dataSourceMap"
            :option="DataPropertiesOption"
            @row-dblclick="handleRowClick"
            @current-row-change="handleCurrentRowChange"
            @cell-click="onHandleSelect"
          ></avue-crud>
        </el-tab-pane>
        <el-tab-pane v-if="model.type == 'SOAP'" label="请求后参数" name="7">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称(回车确认)</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" size="mini" type="danger"><i class="el-icon-delete"></i>删除</el-button>
            </div>
          </div>
          <avue-crud ref="RequestPropertiesCrud" v-model="model" :option="RequestParams"></avue-crud>
        </el-tab-pane>
        <el-tab-pane label="主键配置" name="5">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称(回车确认)</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary" @click="addDataSourceRow('MainPropertiesCrud')">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" size="mini" @click="onHandleDelete('MainPropertiesCrud')" type="danger"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="MainPropertiesCrud"
            v-model="model"
            :data="dataMainMap"
            @row-dblclick="handleRowClick"
            @cell-click="onHandleMainSelect"
            :option="MainPropertiesOption"
          ></avue-crud>
        </el-tab-pane>
        <el-tab-pane label="执行后SQL" name="6">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称(回车确认)</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="mini" type="primary" @click="addDataSourceRow('AfterPropertiesCrud')">新增</el-button>
              <el-button class="el-button el-button--danger el-button--small is-plain" size="mini" @click="onHandleDelete('AfterPropertiesCrud')" type="danger"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="AfterPropertiesCrud"
            v-model="model"
            :data="dataAfterMap"
            :option="AfterPropertiesOption"
            @cell-click="onHandleAfterSelect"
            @row-dblclick="handleRowClick"
          ></avue-crud>
        </el-tab-pane>
      </el-tabs>
      <span v-if="dialogTitle != '查看'" slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submit">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="showDialog = false">取消</el-button>
      </span>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/importconfig';
import { mapGetters } from 'vuex';
import { deepClone, getIlistId, cutSameItem } from '@/util/util';

import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    const obj = {
      submitBtn: false,
      emptyBtn: false,
      labelWidth: '110'
    };
    return {
      form: {},
      query: {},
      tableOption: {},
      dataSourceMap: [], // 数据映射配置
      dataMainMap: [], //主键配置
      dataAfterMap: [], //执行后sql
      writeDataSourceMap: [], //写入数据源
      readDataSourceMap: [], //读取数据源
      dataIndex: -1,
      mainIndex: -1,
      afterIndex: -1,
      writeIndex: -1,
      readIndex: -1,
      loading: true,
      dialogClose: false, // 查看的弹框补能关闭
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        addBtn: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchSpan: 7,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        // menu: false,
        tip: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '类名',
            prop: 'className',
            search: true
          },
          {
            label: 'SOAP地址',
            hide: true,
            prop: 'soapWsdlUrl'
          },
          {
            label: 'SOAP命名空间',
            hide: true,
            prop: 'soapNameSpace'
          },
          {
            label: 'SOAP服务名称',
            hide: true,
            prop: 'soapServiceName'
          },
          {
            label: 'SOAP响应名称',
            hide: true,
            prop: 'soapResponseName'
          },
          {
            label: 'SOAP参数',
            hide: true,
            prop: 'soapParamJson'
          },
          {
            label: 'SOAP最后同步日期',
            hide: true,
            prop: 'soapParamLastSyncDateTime'
          },
          {
            label: 'REST地址',
            prop: 'restUrl'
          },
          {
            label: 'REST数据源',
            prop: 'restDataField'
          },
          {
            label: '类型',
            prop: 'type'
          },
          {
            label: '序号',
            prop: 'sequence'
          },
          {
            label: '最后同步开始时间',
            prop: 'updateTime'
          },
          {
            label: '最后同步结束时间',
            prop: 'updateTime'
          },
          {
            label: '最后同步状态',
            prop: 'status'
          },
          {
            label: '执行删除',
            prop: 'isExecuteDelete',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '初始化SQL',
            prop: 'initSqlString'
          },
          {
            label: '增量SQL',
            hide: true,
            prop: 'deltaSqlString'
          },
          {
            label: '主键SQL',
            hide: true,
            prop: 'primaryKeySqlString'
          },
          {
            label: '倒推时长',
            hide: true,
            prop: 'backMinutes'
          },
          {
            label: '数据源id',
            prop: 'basicDataSourceId'
          },
          {
            label: '回写数据源id',
            hide: true,
            prop: 'writeInBasicDataSourceId'
          }
        ]
      },
      data: [],
      showDialog: false,
      dialogTitle: '新增',
      model: {
        type: 'DATABASE',
        writeInBasicDataSources: [],
        basicDataSources: [],
        classConfigFieldMappings: [],
        primaryKeys: [],
        afterSqlStrings: []
      }, //基本属性信息
      tabsIndex: '1', //选项卡下标
      basicPropertiesOption: {
        ...obj,
        column: [
          {
            label: '编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类名',
            prop: 'className',
            rules: [
              {
                required: true,
                message: '请输入类名',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'type',
            type: 'select',
            hide: true,
            event: 'selectionChange',
            dicData: [
              {
                label: 'DATABASE',
                value: 'DATABASE'
              },
              {
                label: 'EXCEL',
                value: 'EXCEL'
              },
              {
                label: 'REST',
                value: 'REST'
              },
              {
                label: 'SOAP',
                value: 'SOAP'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入类型',
                trigger: 'blur'
              }
            ],
            change: ({ value, column }) => {
              const crtRef = this.$refs.basicPropertiesForm.option.column;
              let REST = this.findObject(crtRef, 'restUrl');
              let DATADIC = this.findObject(crtRef, 'dataDic');
              let USERNAME = this.findObject(crtRef, 'userName');
              let PASSWORD = this.findObject(crtRef, 'passWord');
              let arr = [REST, DATADIC, USERNAME, PASSWORD];
              if (value !== 'REST') {
                arr && arr.forEach((k) => (k.display = false));
              } else {
                arr && arr.forEach((k) => (k.display = true));
              }
            }
          },
          {
            label: '序号',
            prop: 'sequence',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入序号',
                trigger: 'blur'
              }
            ]
          },
          { label: 'REST地址', prop: 'restUrl' },
          {
            label: 'REST数据源',
            prop: 'restDataField'
          },
          { display: false, label: '数据字段', prop: 'dataDic' },
          { display: false, label: '用户名', prop: 'userName' },
          { display: false, label: '密码', prop: 'passWord' },
          {
            label: '倒推时长',
            prop: 'backMinutes',
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入倒推时长',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '启用',
            prop: 'switch',
            type: 'switch',
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            hide: true
          },
          {
            label: '执行删除',
            prop: 'isExecuteDelete',
            type: 'switch',
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            hide: true
          },
          {
            label: '备注',
            prop: 'textarea',
            type: 'textarea',
            maxRows: 3,
            minRows: 3
          }
        ]
      }, //基本属性内容配置
      warehousePropertiesOption1: {
        ...obj,
        menu: false,
        addBtn: false, //添加按钮
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        highlightCurrentRow: true,
        maxHeight: '200',
        // saveBtnText: false,  //保存按钮
        column: [
          {
            label: '数据源名称',
            prop: 'name'
          },
          {
            label: '数据源编码',
            prop: 'code'
          },
          {
            label: '驱动名称',
            prop: 'driverClass'
          },
          {
            label: '链接地址',
            prop: 'url'
          },
          {
            label: '用户名',
            prop: 'username'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      }, //数据源配置1
      warehousePropertiesOption2: {
        ...obj,
        menu: false,
        addBtn: false, //添加按钮
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        highlightCurrentRow: true,
        maxHeight: '200',
        // saveBtnText: false,  //保存按钮
        column: [
          {
            label: '数据源名称',
            prop: 'name'
          },
          {
            label: '数据源编码',
            prop: 'code'
          },
          {
            label: '驱动名称',
            prop: 'driverClass'
          },
          {
            label: '链接地址',
            prop: 'url'
          },
          {
            label: '用户名',
            prop: 'username'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      }, //数据源配置2
      SqlPropertiesOption: {
        ...obj,
        column: [
          {
            label: '初始化SQL',
            prop: 'initSqlString',
            type: 'textarea',
            span: 20,
            rules: [
              {
                required: true,
                message: '初始化SQL',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '增量SQL',
            prop: 'deltaSqlString',
            type: 'textarea',
            span: 20,
            rules: [
              {
                required: true,
                message: '增量SQL',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '主键SQL',
            prop: 'primaryKeySqlString',
            type: 'textarea',
            span: 20,
            rules: [
              {
                required: true,
                message: '主键SQL',
                trigger: 'blur'
              }
            ]
          }
        ]
      }, //SQL数据配置
      DataPropertiesOption: {
        ...obj,
        menu: false,
        index: true,
        addBtn: false, //添加按钮
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        cellBtn: true,
        highlightCurrentRow: true, // 选中高亮
        column: [
          {
            label: '数据源字段',
            prop: 'fieldName',
            cell: true,
            // $cellEdit: true,
            change: ({ row, column }) => {}
          },
          {
            label: '本地数据字段',
            prop: 'innerFieldName',
            cell: true
          },
          {
            label: '转换配置',
            prop: 'fieldValueConver',
            cell: true
          },
          {
            label: '默认值',
            prop: 'defaultValue',
            cell: true
          }
        ]
      }, //数据映射配置
      MainPropertiesOption: {
        ...obj,
        menu: false,
        index: true,
        addBtn: false,
        addRowBtn: false,
        highlightCurrentRow: true, // 选中高亮
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        cellBtn: true, //cellBtn设置为true则开启行编辑按钮
        column: [
          {
            label: '本地数据字段',
            prop: 'primaryKeys',
            cell: true //编辑的字段设置cell为true
          }
        ]
      }, //主键配置
      AfterPropertiesOption: {
        ...obj,
        menu: false,
        index: true,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        addRowBtn: false,
        cellBtn: true,
        highlightCurrentRow: true, // 选中高亮
        column: [
          {
            label: '执行后SQL',
            prop: 'afterSqlStrings',
            cell: true //编辑的字段设置cell为true
          }
        ]
      }, //执行后SQl配置
      RequestParams: {
        menu: false,
        index: true,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        addRowBtn: false,
        cellBtn: true,
        highlightCurrentRow: true, // 选中高亮
        column: [
          {
            label: '参数名称',
            prop: 'dataSource2',
            cell: true //编辑的字段设置cell为true
          },
          {
            label: '参数值',
            prop: 'dataSource3',
            cell: true //编辑的字段设置cell为true
          }
        ]
      } //请求参数
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.importconfig_add, false),
        viewBtn: this.vaildData(this.permission.importconfig_view, false),
        delBtn: this.vaildData(this.permission.importconfig_delete, false),
        editBtn: this.vaildData(this.permission.importconfig_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 打开模态框
     */
    openCommonModal(val) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        titleInfo: val,
        modalTitle: '选择数据源',
        url: '/api/mes-admin/datasource/page',
        isPage: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '数据源名称',
            prop: 'name',
            search: true
          },
          {
            label: '数据源编码',
            prop: 'code'
          },
          {
            label: '驱动名称',
            prop: 'driverClass'
          },
          {
            label: '链接地址',
            prop: 'url'
          },
          {
            label: '用户名',
            prop: 'username'
          },
          {
            label: '密码',
            prop: 'password'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },

    getSelectedRows(rowData, titleInfo) {
      titleInfo === 'writeData' ? this.writeDataSourceMap.push(rowData) : this.readDataSourceMap.push(rowData);
      if (this.writeDataSourceMap && this.writeDataSourceMap.length > 0) {
        this.writeDataSourceMap = cutSameItem(this.writeDataSourceMap);
      }
      if (this.readDataSourceMap && this.readDataSourceMap.length > 0) {
        this.readDataSourceMap = cutSameItem(this.readDataSourceMap);
      }
    },

    /**
     * 双击事件数据源映射配置
     */
    handleRowClick(row, column) {
      if (!row) return;
      if (['fieldName', 'innerFieldName', 'fieldValueConver', 'defaultValue'].includes(column.property)) {
        row.$cellEdit == true ? (row.$cellEdit = false) : this.$refs.DataPropertiesCrud.rowCell(row, row.$index);
      } else if (['primaryKeys'].includes(column.property)) {
        row.$cellEdit == true ? (row.$cellEdit = false) : this.$refs.MainPropertiesCrud.rowCell(row, row.$index);
      } else if (['afterSqlStrings'].includes(column.property)) {
        row.$cellEdit == true ? (row.$cellEdit = false) : this.$refs.AfterPropertiesCrud.rowCell(row, row.$index);
      }
    },

    /**
     * 行单选数据映射
     */
    handleCurrentRowChange(row) {},

    onHandleSelect(row) {
      if (!row) return;
      this.dataIndex = row.$index;
      this.$refs.DataPropertiesCrud.setCurrentRow(row);
    },

    onHandleMainSelect(row) {
      if (!row) return;
      this.mainIndex = row.$index;
      this.$refs.MainPropertiesCrud.setCurrentRow(row);
    },

    onHandleAfterSelect(row) {
      if (!row) return;
      this.afterIndex = row.$index;
      this.$refs.AfterPropertiesCrud.setCurrentRow(row);
    },

    onHandleWriteSelect(row) {
      if (!row) return;
      this.writeIndex = row.$index;
      this.$refs.warehousePropertiesCrud1.setCurrentRow(row);
    },

    onHandleReadSelect(row) {
      if (!row) return;
      this.readIndex = row.$index;
      this.$refs.warehousePropertiesCrud2.setCurrentRow(row);
    },

    selectionChange(val) {},

    addBtn(valueBtn) {
      this.showDialog = true;
      this.dialogClose = false;
      this.dialogTitle = '新增';
      this.model = {
        type: 'DATABASE'
      };
      // this.tabsIndex = '1'
      this.$nextTick(() => {
        this.publicInit(false);
      });
    },

    addDataSourceRow(titleVal) {
      this.$refs[titleVal].rowCellAdd({
        cell: true
      });
    },

    closeDialog() {
      this.publicInit();
      this.model = {};
      this.tabsIndex = '1';
    },

    submit() {
      let validDate1 = new Promise((resolve, reject) => {
        this.$refs.basicPropertiesForm.validate((valid, done) => {
          const { initSqlString, deltaSqlString, primaryKeySqlString } = this.model;
          //   console.log(valid, 'validDate1validDate1', this.model);
          if (valid && initSqlString && deltaSqlString && primaryKeySqlString) {
            this.dialogTitle === '新增' ? this.fooMethods(add) : this.fooMethods(update);
          } else {
            this.tabsIndex = '1';
          }
          done();
        });
      });

      let validData2 = new Promise((resolve, reject) => {
        this.$refs.SqlPropertiesForm.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '3';
          }
        });
      });
      Promise.all([validDate1, validData2]).then(() => {
        console.log(validDate1, 'validDate1', validData2, 'validData2validData2');
        if (this.dialogTitle === '新增') {
          add(attribute).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '新增成功!'
              });
              this.showDialog = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
          done();
        } else if (this.dialogTitle === '编辑') {
          update(attribute).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '编辑成功!'
              });
              this.showDialog = false;
            },
            (error) => {
              console.log(error);
            }
          );
          done();
        }
        // })
      });
    },

    /**
     * 新增/编辑方法
     */
    async fooMethods(foo) {
      this.tabsIndex = '1';
      const params = deepClone(this.model);
      params['writeInBasicDataSources'] = getIlistId(this.writeDataSourceMap);
      params['basicDataSources'] = getIlistId(this.readDataSourceMap);
      params['classConfigFieldMappings'] =
        this.dataSourceMap &&
        this.dataSourceMap.map(({ defaultValue, fieldName, fieldValueConver, innerFieldName }) => ({
          defaultValue,
          fieldName,
          fieldValueConver,
          innerFieldName,
          importConfigId: params.id
        }));
      params['primaryKeys'] =
        this.dataMainMap &&
        this.dataMainMap.reduce((pre, crt) => {
          pre.push(crt['primaryKeys']);
          return pre;
        }, []);
      params['afterSqlStrings'] =
        this.dataAfterMap &&
        this.dataAfterMap.reduce((pre, crt) => {
          pre.push(crt['afterSqlStrings']);
          return pre;
        }, []);
      delete params['extFields'];
      const { data: res } = await foo(params);
      if (res.code !== 200) {
        window.console.log(res.msg);
        return;
      }
      this.onLoad(this.page);
      this.$message({
        type: 'success',
        message: `${this.dialogTitle}成功!`
      });
      this.showDialog = false;
    },

    getDetailInfo(row) {
      getDetail(row.id).then((res) => {
        this.model = res.data.data;
        this.writeDataSourceMap = this.model.writeInBasicDataSources.filter((k) => k);
        this.readDataSourceMap = this.model.basicDataSources;
        this.dataSourceMap = this.model.classConfigFieldMappings;
        this.dataMainMap = deepClone(this.model.primaryKeys).map((k) => {
          return { primaryKeys: k };
        });
        this.dataAfterMap = deepClone(this.model.afterSqlStrings).map((k) => {
          return { afterSqlStrings: k };
        });
      });
    },

    /**
     * 公共初始化方法
     * 默认时重置的状态
     */
    publicInit(type = 'rest') {
      this.dataSourceMap = new Array();
      this.writeDataSourceMap = new Array();
      this.readDataSourceMap = new Array();
      this.dataMainMap = new Array();
      this.dataAfterMap = new Array();
      let arr = Object.keys(this.$refs).filter((k) => k.includes('Form'));
      arr &&
        arr.forEach((item) => {
          if (this.$refs[item] != void 0) {
            if (type == 'rest') {
              // Todo: 这里需要区分编辑状态下才能用resetForm
              this.dialogTitle === '编辑' ? this.$refs[item].resetFields() : this.$refs[item].clearValidate();
            } else {
              this.$refs[item].allDisabled = type;
            }
          }
        });
    },

    /**
     * 查看详情
     */
    rowView(row) {
      this.dialogClose = true;
      this.showDialog = true;
      this.dialogTitle = '查看';
      this.$nextTick(() => this.publicInit(true));
      this.getDetailInfo(row);
    },

    /**
     * 修改物料数据
     */
    rowUpdate(row) {
      this.dialogClose = false;
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.getDetailInfo(row);
    },

    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },

    /**
     * 数据源映射删除
     */
    onHandleDelete(titleCrud) {
      let obj = {
        DataPropertiesCrud: () => {
          this.dataSourceMap.splice(this.dataIndex, 1);
        },
        MainPropertiesCrud: () => {
          this.dataMainMap.splice(this.mainIndex, 1);
        },
        AfterPropertiesCrud: () => {
          this.dataAfterMap.splice(this.afterIndex, 1);
        },
        warehousePropertiesCrud1: () => {
          this.writeDataSourceMap.splice(this.writeIndex, 1);
        },
        warehousePropertiesCrud2: () => {
          // this.readDataSourceMap = this.readDataSourceMap.filter(({ $index }) => this.readIndex != $index);
          this.readDataSourceMap.splice(this.readIndex, 1);
        }
      };
      this.$refs[titleCrud].setCurrentRow(null);
      obj[titleCrud]();
    },

    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tabs--border-card > .el-tabs__content {
  padding: 0 10px 0;
}

.el-tabs__content {
  #pane-2,
  #pane-4,
  #pane-5,
  #pane-6,
  #pane-7 {
    .el-card__body {
      .avue-crud__menu {
        display: none;
      }
    }
  }
}
.top-title-flex {
  padding-top: 5px;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center !important;
}
</style>
